<template>
  <component
    :is="isShowRules ? 'el-form-item' : 'div'"
    :prop="scope.column.property"
    :rules="editConfig.rules"
    :class="[editConfig.className, 'single_edit_cell']"
    v-bind="$attrs"
  >
    <!-- 编辑组件自定义插槽 -->
    <template v-if="editConfig.editSlotName">
      <div :class="prop" @keyup="keyUpHandle">
        <slot :name="editConfig.editSlotName" :scope="scope" />
      </div>
    </template>
    <div>{{ scope.row[prop] }}</div>
    <div
      v-if="
        scope.row.isSelected &&
        (columnItem.editable == null || columnItem.editable) &&
        (!columnItem.currentEdit || (columnItem.currentEdit && !scope.row.currentEdit))
      "
      class="edit-hover__class"
      :class="{
        'common-text-ellipsis': !isTextWrap,
        'cell-change__class': valueIsChanged(scope.row, scope.$index, index),
      }"
      @click="handleChangeEditCell(scope.$index, index)"
    >
      <span v-if="columnItem.editType == 'select'">
        {{ valueToLabel(scope.row[columnItem.prop], columnItem.options) }}
      </span>
      <span v-else>
        {{ scope.row[columnItem.prop] }}
      </span>
    </div>
    <el-input
      v-if="
        (columnItem.editType == 'input' || columnItem.editType == null) &&
        scope.row.isSelected &&
        scope.row.currentEdit &&
        columnItem.currentEdit
      "
      v-model="scope.row[scope.column.property]"
      @change="editChange(scope.$index, index)"
      :placeholder="'请输入' + columnItem.label"
    ></el-input>
    <el-select
      v-if="columnItem.editType == 'select' && scope.row.isSelected && scope.row.currentEdit && columnItem.currentEdit"
      v-model="scope.row[scope.column.property]"
      @change="editChange(scope.$index, index)"
      :placeholder="'请选择' + columnItem.label"
      v-bind="{ ...columnItem.selectBinds, ...$attrs }"
    >
      <el-option v-for="item in columnItem.options" :key="item.value" :label="item.label" :value="item.value" />
    </el-select>
    <el-time-picker
      v-if="
        columnItem.editType === 'time-picker' && scope.row.isSelected && scope.row.currentEdit && columnItem.currentEdit
      "
      value-format="HH:mm:ss"
      v-model="scope.row[scope.column.property]"
      placeholder="请选择"
    />
    <el-date-picker
      v-if="
        columnItem.editType === 'date-picker' && scope.row.isSelected && scope.row.currentEdit && columnItem.currentEdit
      "
      v-model="scope.row[scope.column.property]"
      @change="editChange(scope.$index, index)"
      placeholder="请选择"
    >
    </el-date-picker>
    <!-- 特殊格式的正常情况展示，select -->
    <div v-if="columnItem.editType == 'select' && !scope.row.isSelected">
      <!-- {{ valueToLabel(scope.row[columnItem.prop], columnItem.options) }} -->
    </div>
    <!-- <component
      v-if="!editConfig.editSlotName"
      :is="editConfig.editComponent || 'el-input'"
      v-model="scope.row[prop]"
      :type="editConfig.type"
      :placeholder="editConfig.placeholder || getPlaceholder(editConfig)"
      ref="parentCom"
      :class="prop"
      @change="handleEvent(editConfig.event, scope.row[prop], editConfig.editComponent)"
      @keyup="keyUpHandle"
      :style="{ width: editConfig.width || '100%' }"
      v-on="cEvent(editConfig)"
      v-bind="
        typeof editConfig.bind == 'function'
          ? editConfig.bind(scope)
          : { clearable: true, filterable: true, ...editConfig.bind }
      "
    > -->
    <!-- 前置文本 -->
    <!-- <template #prepend v-if="editConfig.prepend">{{ editConfig.prepend }}</template> -->
    <!-- 后置文本 -->
    <!-- <template #append v-if="editConfig.append">{{ editConfig.append }}</template> -->
    <!-- 子组件自定义插槽 -->
    <!-- <template v-if="editConfig.childSlotName">
          <slot />
        </template>-->
    <!-- <template v-if="!editConfig.editComponent.includes('date')">
        <component
          :is="compChildName(editConfig)"
          v-for="(value, key, index) in listTypeInfo[editConfig.list]"
          :key="index"
          :disabled="value.disabled"
          :label="compChildLabel(editConfig, value)"
          :value="compChildValue(editConfig, value, key)"
          >{{ compChildShowLabel(editConfig, value) }}</component
        >
      </template>
    </component> -->
  </component>
</template>

<script setup lang="ts" name="SingleEditCell">
import { computed, ref } from 'vue'
import { valueToLabel } from '@/utils/common.js'

const props = defineProps({
  /** 编辑配置项说明
   * label: '爱好', // placeholder显示
   * editComponent: 'el-select', // 组件
   * type: 'select-arr', // option显示
   * list: 'hobbyList', // 下拉选择数据源
   * arrLabel: 'label', // 下拉选择中文显示
   * arrKey: 'value' // 下拉选择number显示（最终传后台）
   * bind:{} // 组件衍生属性（即第三方组件属性）
   */
  columnItem: {
    type: Object,
    default: () => {
      return {}
    },
  },
  editConfig: {
    type: Object,
    default: () => ({}),
  },
  // 下拉选择数据源
  listTypeInfo: {
    type: Object,
    default: () => ({}),
  },
  scope: {
    type: Object,
    default: {},
  },
  prop: {
    type: String,
    default: '',
  },
  // 是否走表单验证（表头合并不校验）
  isShowRules: {
    type: Boolean,
    default: true,
  },
  // modelValue: {
  //   type: [String, Number, Array, Boolean],
  // },
})
// 编辑修改对应的数组，[rowIndex, columnIndex]
const changeValueIndexs = ref([])
const editChange = (rowIndex, columnIndex) => {
  changeValueIndexs.value.push(`${rowIndex}-${columnIndex}`)
  //   cloneTableData.value[rowIndex].valueChange = true
  //   cloneColumnList.value[columnIndex].valueChange = true
}
// 判断当前行是否被修改过, 只计算被选中行
const valueIsChanged = (row, rowIndex, columnIndex) => {
  if (row.isSelected && changeValueIndexs.value.length > 0) {
    let temp = changeValueIndexs.value.find((item) => item == `${rowIndex}-${columnIndex}`)
    return temp
  }
}
const handleChangeEditCell = (rowIndex, columnIndex) => {
  cloneTableData.value.forEach((e, index) => {
    if (rowIndex === index) {
      e.currentEdit = true
    } else {
      e.currentEdit = false
    }
  })
  cloneColumnList.value.forEach((e, index) => {
    if (columnIndex === index) {
      e.currentEdit = true
    } else {
      e.currentEdit = false
    }
  })
}
// 抛出事件
const emits = defineEmits(['handleEvent', 'update:modelValue', 'keyupHandle'])
// const childValue = ref(props.scope?.row[props?.prop])
// vue3 v-model简写
// let childValue: any = computed({
//   get() {
//     return props.scope?.row[props.scope?.column?.property]
//     // return props.scope?.row[props?.prop]
//   },
//   set(val) {
//     console.log('update:modelValue', val)
//     emits('update:modelValue', val)
//   },
// })
// watch(
//   () => childValue.value,
//   (data) => emits('update:modelValue', data)
// )
// 键盘事件
const keyUpHandle = ($event) => {
  emits('keyupHandle', $event, props.scope.$index, props.prop)
}
// 引用第三方事件
// const cEvent = computed(() => {
//   return (editConfig: any) => {
//     let event = { ...editConfig.eventHandle }
//     let changeEvent = {}
//     Object.keys(event).forEach((v) => {
//       changeEvent[v] = (e) => {
//         if (e) {
//           event[v] && event[v](e, props.prop)
//         } else {
//           event[v] && event[v](props.prop)
//         }
//       }
//     })
//     return { ...changeEvent }
//   }
// })
// 子组件名称
// const compChildName = computed(() => {
//   return (editConfig: any) => {
//     switch (editConfig.type) {
//       case 'checkbox':
//         return 'el-checkbox'
//       case 'radio':
//         return 'el-radio'
//       case 'select-arr':
//       case 'select-obj':
//         return 'el-option'
//     }
//   }
// })
// 子子组件label
// const compChildLabel = computed(() => {
//   return (editConfig: any, value) => {
//     switch (editConfig.type) {
//       case 'radio':
//       case 'checkbox':
//         return value.value
//       case 'el-select-multiple':
//       case 'select-arr':
//         return value[editConfig.arrLabel || 'dictLabel']
//       case 'select-obj':
//         return value
//     }
//   }
// })
// 子子组件value
// const compChildValue = computed(() => {
//   return (editConfig: any, value, key) => {
//     switch (editConfig.type) {
//       case 'radio':
//       case 'checkbox':
//         return value.value
//       case 'el-select-multiple':
//       case 'select-arr':
//         return value[editConfig.arrKey || 'dictValue']
//       case 'select-obj':
//         return key
//     }
//   }
// })
// 子子组件文字展示
// const compChildShowLabel = computed(() => {
//   return (editConfig: any, value) => {
//     switch (editConfig.type) {
//       case 'radio':
//       case 'checkbox':
//         return value.label
//       case 'el-select-multiple':
//       case 'select-arr':
//         return value[editConfig.arrLabel || 'dictLabel']
//       case 'select-obj':
//         return value
//     }
//   }
// })
// placeholder的显示
// const getPlaceholder = (row: any) => {
//   let placeholder
//   if (row.comp && typeof row.comp == 'string') {
//     if (row.comp.includes('input')) {
//       placeholder = '请输入' + row.label
//     } else if (row.comp.includes('select') || row.comp.includes('date')) {
//       placeholder = '请选择' + row.label
//     } else {
//       placeholder = row.label
//     }
//   }
//   return placeholder
// }
// 绑定的相关事件
const handleEvent = (type, val, editCom) => {
  // console.log('组件', type, val, editCom)
  emits('handleEvent', { type, val })
}
</script>
<style lang="scss">
.single_edit_cell {
  cursor: pointer;
}
</style>
